package com.smt.controller;

import com.smt.utils.ThreadPoolUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @autor xiaoyu.fang
 * @date 2019/9/4 14:27
 */
@Slf4j
@RestController
@RequestMapping("/springboot")
public class DemoController {

    @Value("${userdefined.username}")
    private String username;

    @GetMapping("/get")
    public BaseVO getInfo(@RequestParam(value = "msg", required = false) String msg) {
        log.info("userName === {}", username);
        return new BaseVO(msg);
    }

    @GetMapping("/done")
    public BaseVO getThread2do() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        List<Future> futureList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            try {
                Future<String> messageFuture = ThreadPoolUtil.submit(new CallableTest(String.format("这是第{%s}条消息", i)));
                futureList.add(messageFuture);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        for (Future<String> message : futureList) {
            String messageData = message.get();
        }
        System.out.println(String.format("共计耗时{%s}毫秒", System.currentTimeMillis() - start));
        return new BaseVO();
    }

}

@Data
class BaseVO {

    private Integer code;

    private String msg;

    BaseVO() {
        this.code = 1;
    }

    BaseVO(String msg) {
        this.code = 0;
        this.msg = msg;
    }
}

class CallableTest implements Callable<String> {

    private String message;

    public CallableTest(String messae) {
        this.message = messae;
    }

    @Override
    public String call() {
        System.out.println(String.format("打印消息：%s", message));
        return "OK";
    }
}